<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\User;
use App\Model\UserShipment;
use App\Service\UserService;
use App\Transformers\UserShipmentTransformer;

class UserController extends Controller
{

    /**
     * 登录，新增或修改用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addOrUpdate(Request $request) {

        $wechat = app('wechat.mini_program');
        $res = $wechat->auth->session($request->code?:'');
        $input = $request->all();
        if(isset($res['errcode']) && $res['errcode'] > 0) return $this->apiError($res['errmsg']);
        $open_id = $res['openid'];
        $validateResult = $this->validateCreateUser($input);
        if ($validateResult["errorCode"] > 0) {
            return $this->apiError($validateResult["message"], $validateResult["errorCode"]);
        }

        $user = User::where('open_id', $open_id)->first();
        if(empty($user)){
            $user = new User();
            $user->open_id = $open_id;
        }
        if(!empty($input['profile'])) $user->profile = $input['profile'];
        if(!empty($input['nick_name'])) $user->nick_name = $input['nick_name'];

        $user->save();

        $data = [
            'user' => $user
        ];

        return $this->apiSuccess($data);
    }

    /**
     * 添加地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addAddress(Request $request) {

        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];
        $input = $request->all();
        $validateResult = $this->validateCreateAddress($input);
        if ($validateResult["errorCode"] > 0) {
            return $this->apiError($validateResult["message"], $validateResult["errorCode"]);
        }

        $address = $this->_setAddress(new UserShipment(), $input, $user);
        $address->save();
        $data['data'] = [
            'shipment' => $this->fractalItem($address, new UserShipmentTransformer())
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 地址列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addressList(Request $request) {
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];

        $user_shipments = UserShipment::where('user_id', $user->id)->paginate(10);
        $data['data'] = [
            'user_shipments' => $this->factalPaginator($user_shipments, new UserShipmentTransformer())
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 删除地址
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteAddress(Request $request, $id) {
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];
        $address = UserShipment::where('user_id', $user->id)->where('id', $id)->first();
        if(empty($address)) return $this->apiError('无效地址');

        $address->delete();
        return $this->apiSuccess();
    }

    /**
     * 修改地址
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateAddress(Request $request, $id) {
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];
        $input = $request->all();
        $validateResult = $this->validateCreateAddress($input);
        if ($validateResult["errorCode"] > 0) {
            return $this->apiError($validateResult["message"], $validateResult["errorCode"]);
        }
        $address = UserShipment::where('user_id', $user->id)->where('id', $id)->first();
        if(empty($address)) return $this->apiError('无效地址');
        $address = $this->_setAddress($address, $input, $user);
        $address->save();
        $data['data'] = [
            'user' => $this->fractalItem($address, new UserShipmentTransformer())
        ];
        return $this->apiSuccess($data);
    }

    private function _setAddress($address, $input, $user) {
        $address->user_id = $user->id;
        $address->contact_mobile = $input['contact_mobile'];
        $address->contact_person = $input['contact_person'];
        $address->area = $input['area'];
        $address->address = $input['address'];
        return $address;
    }

    private function validateCreateAddress($input) {
        $contact_mobile = isset($input['contact_mobile']) ? $input['contact_mobile']: '';
        $contact_person = isset($input['contact_person']) ? $input['contact_person']: '';
        $area = isset($input['area']) ? $input['area']: '';
        $address = isset($input['address']) ? $input['address']: '';
        if(empty($contact_mobile)){
            return [
                "message" => "手机不得为空",
                "errorCode" => 5000
            ];
        }
        if(empty($contact_person)){
            return [
                "message" => "收货人不得为空",
                "errorCode" => 5000
            ];
        }
        if(empty($area)){
            return [
                "message" => "地区不得为空",
                "errorCode" => 5000
            ];
        }
        if(empty($address)){
            return [
                "message" => "详细地址不得为空",
                "errorCode" => 5000
            ];
        }
        return [
            "message" => "没有错误信息",
            "errorCode" => 0
        ];

    }

    private function validateCreateUser($input) {
        $name = isset($input['name']) ? $input['name']: '';
        $mobile = isset($input['mobile']) ? $input['mobile']: '';
        if(!empty($mobile)){
            return [
                "message" => "手机格式有误",
                "errorCode" => 5000
            ];
        }
        return [
            "message" => "没有错误信息",
            "errorCode" => 0
        ];

    }
}
